 
import { ABaseDecision } from "GameLoop/DecisionMaking/BaseDecision";
import { CacheDataHostiles } from "GameLoop/WorldState/PollingStation/PollingTasks/RoomItem/CacheHostiles";
 
import { priority } from "utils/constants/definetypes";
import { UtilsHelper } from "utils/position/UtilsHelper";
import { TaskHelper } from "utils/task/TaskHelper";
 
import { WarStrategy } from "utils/war/WarStrategy";

/**
 * 房间防守决策,就按
 */
export class DefendMyRoomDecision< T extends "team"|"room"="team"|"room"> extends ABaseDecision<T>
{
   
    public isExpired(event: NormalEvent, region: string): boolean 
    {
        
        const room = Game.rooms[event.region];
        const task = room.getTaskById(`${event.room}_defend`,["room","team"]);
        if(task )
        {
            
            return false;
        }
        return true;
    }
    public makeTask(event: NormalEvent, region: string): IDecisionCode<T>|false
    {
         
        const room = Game.rooms[event.region] as Required<Room>;
        const task = this.makeDefendTask(event);
        if(task)
        {
            const code:IDecisionCode<T>={
                region:event.region,
                isunique:false,
                task:[task as any ],
            }
            return code
        }
       
        return false;
        // return code
    }
 
    public makeDefendTask(event: NormalEvent  ):ITask|undefined|false
    {
        global.Log.Debug(`${event.region}有敌人来犯`,"房间防守决策");
        const room = Game.rooms[event.region] as Required<Room>;
        const hostcreeps  =room.getWorld().PollHostiles(event.room);
        if(!hostcreeps)
        {
            global.Log.Debug(`${event.region}有敌人来犯`,"找不到敌人");
            return undefined
        }

        if(hostcreeps.cacheData && hostcreeps.cacheData.length>0)
        {
            const cachestructures =   room.getWorld().PollStructure(event.room);
            if(room.towers().length && cachestructures )
            {
                const status = WarStrategy.getEnemystatus(hostcreeps.cacheData.map(e=>Game.getObjectById(e.id)).filter(e=>e) as Creep[],cachestructures);
                room.memory.warinfo={
                    enemy:status.hostileCreeps.map(e=>e.id)
                }
             
                const damage_sum = status.attack+status.rangeAttack;
                if(damage_sum>400 && status.heal>=status.max_damage   &&  status.enemyCount>0)
                {
                    Memory.Debug[`主防测试${event.room}`] = {
                        heal:status.heal,         // 敌方单位治疗总量
                        max_damage:status.max_damage,           // 防御塔对敌方造成的最大伤害
                        attack:status.attack, // 敌方单位伤害总量
                        rangeAttack:status.rangeAttack,
                        enemyCount:status.enemyCount,  // 非NPC的敌方单位数量
                        hostileCreeps:status.hostileCreeps.map(e=>e.body), // 敌方的爬
                        
                    };
                    const lab = room.getEntity("LabEntity").Labs();
                    if(lab.length>0 && !room.controller.safeMode)
                    {
                        // if(room.controller.level>6 || ((room.controller.level ==6)&& room.activeSafeMode() != OK))
                        {
                            // 主动主防
                            return this.ramDefendTask(room,event.room,status);
                        }
                    }
                    else
                    {
                        // 没有lab
                        if(room.activeSafeMode() === OK)
                        {
                            // 没有lab则激活sf
                        }
                        else
                        {   
                            // 没有sf 就要请求其他房间援助
                        }
                        global.Log.Debug(`${event.region}有敌人来犯`,`未处理条件`);
                        return undefined
                    }
                   
                }
                else
                {
                    // 防御塔击杀
                    
                    if(cachestructures.getStructure(STRUCTURE_TOWER))
                    {
                        global.Log.Debug(`${event.region}有敌人来犯`,"防御塔击杀");
                        return this.towerDefendTask(event);
                    }
                    else
                    {
                        const task  = this.warDefendTask(room,event.room,hostcreeps)
                        if(task)
                        {
                            return task;
                        }
                        else
                        {
                            room.log("warn","无法计算出防御计划")
                            global.Log.Debug(`${event.region}有敌人来犯`,"无法计算出防御计划1");
                            return undefined
                        }
                    }
                }
            }
            else
            {
                const status = WarStrategy.getEnemystatus(hostcreeps.cacheData.map(e=>Game.getObjectById(e.id)) as Creep[] );
                // 没有防御塔
                if(status.enemyCount>0)
                {
                    if(room.activeSafeMode() == OK)
                    {
                        return undefined;
                    }
                }
                const task  = this.warDefendTask(room,event.room,hostcreeps)
                if(task)
                {
                    return task;
                }
                else
                {
                    room.log("warn","无法计算出防御计划")
                    global.Log.Debug(`${event.region}有敌人来犯`,"无法计算出防御计划2");
                    return undefined
                }
            }
        }
        else 
        {
            global.Log.Debug(`${event.region}有敌人来犯`,`找不到敌人2 ${JSON.stringify(hostcreeps.cacheData)}`);
            return undefined
        }
       
    }
    

    private towerDefendTask(event: NormalEvent )
    {
        const task :ITask<IRoomTaskData<"towerDefend">>={
            id:`${event.room}_defend`,
            priority:priority.S,
            ttl:5000,
            type:"tower",
            data:{
                type:"towerDefend",
                arg:{
                    roomName:event.room,
                    
                },
            },
            shard:0,
        }
        return task
    }


    private warDefendTask(room:Required<Room>,defendRoom:string,hostcreeps:CacheDataHostiles<ICacheHostileCreep>)
    {
        global.Log.Debug(`${defendRoom}有敌人来犯 低等级防御`,"低等级防御");
        const hostileCreeps:Creep[]=[];
        for(const e of hostcreeps.cacheData)
        {
            const creep = Game.getObjectById(e.id);
            if(creep)
            {
                hostileCreeps.push(creep);
            }
        }
        // 没有建筑,激活低等级防御兵
        const plan =WarStrategy.createPlan(room,hostileCreeps);
        if(!plan)
        {
            return false
        }
        global.Log.Debug(`${defendRoom}有敌人来犯 低等级防御`,JSON.stringify(plan));
        const wartask:ITeamTaskData<"defend">  ={
            type:"defend",
            room:defendRoom,
            arg:{
                // creepTrack:{},
                benchRooms:[],
                enemy: hostileCreeps.map(e=>e.id),
                structures:[],
            },
            cost:TaskHelper.getTaskPathCost(room.name,defendRoom),
            creeps:[],
            teams:{} as any,
            creepRequired: plan.creep,
            required:[],
        }
        const teamTask:ITaskDeclare["team"]=
        {
            id:`${defendRoom}_defend`,
            priority: priority.A,
            ttl: 3000,
            type: "team",
            data: wartask,
            shard: 0
        }
        return teamTask
    }

    // 主动防御任务
    private ramDefendTask(room:Required<Room>,defendRoom:string,status: IEnemyTeamSats)
    {
        // 主动主防
        const plan = WarStrategy.createPlanOfDefend(room, status);
        const wartask:ITeamTaskData<"defendram">  ={
            type:"defendram",
            room:defendRoom,
            arg:{
                // creepTrack:{},
                benchRooms:[],
                enemy: status.hostileCreeps.map(e=>e.id),
                structures:[],
            },
            cost:TaskHelper.getTaskPathCost(room.name,defendRoom),
            creeps:[],
            teams:{} as any,
            creepRequired: plan.creep,
            required:[],
        }
        const teamTask:ITaskDeclare["team"]=
        {
            id:`${defendRoom}_defend`,
            priority: priority.A,
            ttl: 3000,
            type: "team",
            data: wartask,
            shard: 0
        }
        return teamTask
    }
}